import { isURL } from '@/utils/validate'
import _ from 'lodash'
import router from '@/router'
import { moduleRoutes } from '@/router'
import type { RouteRecordRaw } from 'vue-router'
/**
 *获取第一个菜单
 * @param {*} routes
 * @returns
 */
export function getFirstMenuItem(menuList=[]) {
  let firstMenuItem = null
  if (menuList[0].childMenus.length) {
    firstMenuItem = menuList[0].childMenus[0]
  } else {
    firstMenuItem = menuList[0]
  }
  return firstMenuItem
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
const viteModules = import.meta.glob('@/views/modules/**/*.vue')
var originMenuList = []
export function fnAddDynamicMenuRoutes(menuList = [], routes: RouteRecordRaw[] = [],init = true) {
  var temp = []
  if(init){
    originMenuList = menuList
  }
  for (var i = 0; i < menuList.length; i++) {
    
    const menu = menuList[i]
    if (menu.childMenus && menu.childMenus.length >= 1) {
      temp = temp.concat(menu.childMenus)
      continue
    }
    // 组装路由
    var route: RouteRecordRaw = {
      path: '',
      component: null,
      name: '',
      meta: {
        // ...window.SITE_CONFIG['contentTabDefault'],
        id: menu.id,
        pid: menu.menuPid,
        routerName: menu.routerName,
        routerPath: menu.routerPath,
        title: menu.menuName,
        // icon: menu.menuIcon,
        isChild: !menu.childMenus.length
      }
    }
    // eslint-disable-next-line
    let URL = (menu.routerPath || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      route['path'] = route['name'] = `i-${menu.id}`
      route['meta']['iframeURL'] = URL
    } else if (/.*:[a-zA-Z]+/.test(URL)) {
      // 如果最后是 path参数
      const idx = URL.lastIndexOf('/')
      const prefixURL = URL.substring(0, idx).replace(/^\//, '').replace(/_/g, '-')
      const pathParam = URL.substring(idx + 1)
      route['path'] = prefixURL.replace(/\//g, '-') + '/' + pathParam
      if (menu.params) {
        route['name'] =
          route['path'] + '-' + _.keyBy(menu.params, 'name')[pathParam.substring(1)]['value']
      }
      // route['component'] = () => import(`@/views/modules/${prefixURL}`)
      route['component'] = viteModules[`/src/views/modules/${prefixURL}/index.vue`]
    } else {
      URL = URL.replace(/^\//, '').replace(/_/g, '-')
      route['path'] = route['name'] = URL.replace(/\//g, '-')
      // route['component'] = () => import(`@/views/modules/${URL}`)
      route['component'] = viteModules[`/src/views/modules/${URL}/index.vue`]
    }

    if (menu.params && menu.params.length > 0) {
      route['meta']['params'] = menu.params
    }
    routes.push(route)
  }
  if (temp.length >= 1) {
    return fnAddDynamicMenuRoutes(temp, routes,false)
  }
  let firstMenuItem = routes.find(item=>{
    return item.meta.id === getFirstMenuItem(originMenuList).id
  })
  if(firstMenuItem){
    moduleRoutes.redirect.name = firstMenuItem.name as string || ''
  }
  // 添加路由
  router.addRoute({
    ...moduleRoutes,
    name: 'main-dynamic-menu',
    children: routes
  } as RouteRecordRaw)
  // router.addRoute({
  //   path: '/:pathMatch(.*)*',
  //   redirect: {
  //     name: '404'
  //   }
  // })
  window.SITE_CONFIG['dynamicHomeRoute'] = firstMenuItem
  window.SITE_CONFIG['dynamicMenuRoutes'] = routes
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
}

export function existRouteComponent(menuList = []){
  let firstMenuItem = getFirstMenuItem(menuList)
  const routerName = (firstMenuItem && firstMenuItem.routerName) || ''
  if (!firstMenuItem || !routerName) {
    return false
  }
  return viteModules[`/src/views/modules/${firstMenuItem.routerPath}/index.vue`]
}
/**
 * 判断当前路由是否为 页面路由/白名单路由
 * @param {*} route 当前路由
 * @param {*} pageRoutes 页面路由，无需登录即可访问
 */
export function fnCurrentRouteIsPageRoute(route, pageRoutes = []) {
  var temp = []
  for (var i = 0; i < pageRoutes.length; i++) {
    if (route.path === pageRoutes[i].path) {
      return true
    }
    if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) {
      temp = temp.concat(pageRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false
}

export function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = decodeURI(window.location.search.substr(1)).match(reg)
  if (r !== null) return unescape(r[2])
  return null
}
